/**
 * @Author: 
 * @Date: 2025-06-30 10:32:17
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-07-03 11:14:57
 * @Description: 检测成果服务
 */
import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Between, Like } from 'typeorm';
import { 
  SoilEtResult,
  CsvFile
} from '../entity/detection-results.entity';
import {
  CreateSoilEtDto,
  UpdateSoilEtDto,
  SoilEtQueryDto,
  SoilEtResponseDto,
  PageResponseDto,
  CsvContentResponseDto,
  CsvStructureDto
} from '../dto/detection-results.dto';
import * as fs from 'fs';
import { parse } from 'csv-parse/sync';
import * as iconv from 'iconv-lite';
// 新增CSV文件相关DTO
export class CreateCsvFileDto {
  originalName: string;
  filePath: string;
  fileSize: number;
}

export class CsvFileResponseDto {
  id: string;
  originalName: string;
  filePath: string;
  fileSize: number;
  createTime: Date;
}

@Provide()
export class DetectionResultsService {
  @InjectEntityModel(SoilEtResult)
  soilEtRepository: Repository<SoilEtResult>;

  @InjectEntityModel(CsvFile)
  csvFileRepository: Repository<CsvFile>;

  // ============= 土含与蒸散发反演成果相关方法 =============

  /**
   * 创建土含蒸散发成果
   */
  async createSoilEt(dto: CreateSoilEtDto): Promise<SoilEtResult> {
    const soilEt = this.soilEtRepository.create(dto);
    return await this.soilEtRepository.save(soilEt);
  }

  /**
   * 根据ID获取土含蒸散发成果
   */
  async getSoilEtById(id: number): Promise<SoilEtResult> {
    const result = await this.soilEtRepository.findOne({
      where: { id }
    });

    if (!result) {
      throw new Error(`ID为${id}的土含蒸散发成果不存在`);
    }

    return result;
  }

  /**
   * 更新土含蒸散发成果
   */
  async updateSoilEt(id: number, dto: UpdateSoilEtDto): Promise<SoilEtResult> {
    const existingResult = await this.getSoilEtById(id);

    Object.assign(existingResult, dto);
    return await this.soilEtRepository.save(existingResult);
  }

  /**
   * 删除土含蒸散发成果
   */
  async deleteSoilEt(id: number): Promise<void> {
    const result = await this.getSoilEtById(id);
    await this.soilEtRepository.remove(result);
  }

 /**
 * 分页查询土含蒸散发成果
 */
async querySoilEt(query: SoilEtQueryDto): Promise<any> {
  const { 
    page = 1, 
    pageSize = 10, 
    resultType, 
    irrigationArea, 
    startDate, 
    endDate,
    etType,           // 新增查询条件
    soilWaterType     // 新增查询条件
  } = query;

  const qb = this.soilEtRepository.createQueryBuilder('soilEt');

  // 添加查询条件
  if (resultType) {
    qb.andWhere('soilEt.resultType LIKE :resultType', { resultType: `%${resultType}%` });
  }

  if (irrigationArea) {
    qb.andWhere('soilEt.irrigationArea LIKE :irrigationArea', { irrigationArea: `%${irrigationArea}%` });
  }

  // 新增 etType 查询条件
  if (etType) {
    qb.andWhere('soilEt.etType LIKE :etType', { etType: `%${etType}%` });
  }

  // 新增 soilWaterType 查询条件
  if (soilWaterType) {
    qb.andWhere('soilEt.soilWaterType LIKE :soilWaterType', { soilWaterType: `%${soilWaterType}%` });
  }

  if (startDate && endDate) {
    qb.andWhere('soilEt.monitorDate BETWEEN :startDate AND :endDate', {
      startDate,
      endDate
    });
  } else if (startDate) {
    qb.andWhere('soilEt.monitorDate >= :startDate', { startDate });
  } else if (endDate) {
    qb.andWhere('soilEt.monitorDate <= :endDate', { endDate });
  }

  // 排序
  qb.orderBy('soilEt.createTime', 'DESC');

  // 分页
  qb.skip((page - 1) * pageSize).take(pageSize);

  const [list, total] = await qb.getManyAndCount();
  const totalPages = Math.ceil(total / pageSize);

  return {
    list,
    total,
    page,
    pageSize,
    totalPages
  };
}

  /**
   * 获取所有土含蒸散发成果(不分页)
   */
  async getAllSoilEt(): Promise<SoilEtResult[]> {
    return await this.soilEtRepository.find({
      order: { createTime: 'DESC' }
    });
  }

  // ============= CSV文件相关方法 =============


/**
 * 读取CSV文件内容
 */
async getCsvContent(id: string, page: number = 1, pageSize: number = 100): Promise<CsvContentResponseDto> {
  const csvFile = await this.getCsvFileById(id);
  
  try {
    // 读取文件内容
    const fileBuffer = fs.readFileSync(csvFile.filePath);
    // 用 gb2312 解码
    const fileContent = iconv.decode(fileBuffer, 'gb2312');
    // 解析CSV
    const records = parse(fileContent, {
      columns: true,
      skip_empty_lines: true,
      trim: true,
      cast: true
    });

    // 获取列名
    const headers = Object.keys(records[0] || {});
    
    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = records.slice(startIndex, endIndex);
    
    const total = records.length;
    const totalPages = Math.ceil(total / pageSize);

    return {
      fileInfo: {
        id: csvFile.id,
        originalName: csvFile.originalName,
        fileSize: csvFile.fileSize,
        createTime: csvFile.createTime
      },
      headers,
      data: paginatedData,
      pagination: {
        page,
        pageSize,
        total,
        totalPages
      }
    };
  } catch (error) {
    throw new Error(`读取CSV文件失败: ${error.message}`);
  }
}

/**
 * 获取CSV文件结构信息
 */
async getCsvStructure(id: string): Promise<CsvStructureDto> {
  const csvFile = await this.getCsvFileById(id);
  
  try {
    const fileContent = fs.readFileSync(csvFile.filePath, 'utf-8');
    const records = parse(fileContent, {
      columns: true,
      skip_empty_lines: true,
      trim: true,
      cast: true
    });

    const headers = Object.keys(records[0] || {});
    const rowCount = records.length;
    
    // 分析每列的数据类型
    const columnTypes: { [key: string]: string } = {};
    if (records.length > 0) {
      headers.forEach(header => {
        const firstValue = records[0][header];
        if (typeof firstValue === 'number') {
          columnTypes[header] = 'number';
        } else if (firstValue instanceof Date) {
          columnTypes[header] = 'date';
        } else {
          columnTypes[header] = 'string';
        }
      });
    }

    return {
      fileInfo: {
        id: csvFile.id,
        originalName: csvFile.originalName,
        fileSize: csvFile.fileSize,
        createTime: csvFile.createTime
      },
      headers,
      rowCount,
      columnTypes,
      sampleData: records.slice(0, 5) // 返回前5行作为样本数据
    };
  } catch (error) {
    throw new Error(`分析CSV文件结构失败: ${error.message}`);
  }
}

  /**
   * 创建CSV文件记录
   */
  async createCsvFile(dto: CreateCsvFileDto): Promise<CsvFile> {
    const csvFile = this.csvFileRepository.create(dto);
    return await this.csvFileRepository.save(csvFile);
  }

  /**
   * 根据ID获取CSV文件
   */
  async getCsvFileById(id: string): Promise<CsvFile> {
    const result = await this.csvFileRepository.findOne({
      where: { id }
    });

    if (!result) {
      throw new Error(`ID为${id}的CSV文件不存在`);
    }

    return result;
  }

  /**
   * 获取所有CSV文件
   */
  async getAllCsvFiles(): Promise<CsvFile[]> {
    return await this.csvFileRepository.find({
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 删除CSV文件
   */
  async deleteCsvFile(id: string): Promise<void> {
    const result = await this.getCsvFileById(id);
    await this.csvFileRepository.remove(result);
  }

  /**
   * 根据文件名查找CSV文件
   */
  async findCsvFileByName(originalName: string): Promise<CsvFile[]> {
    return await this.csvFileRepository.find({
      where: { 
        originalName: Like(`%${originalName}%`) 
      },
      order: { createTime: 'DESC' }
    });
  }
}